package cn.unknowpupil.service.system.impl;

import cn.unknowpupil.common.core.constant.SecurityConstants;
import cn.unknowpupil.common.core.constant.UserConstants;
import cn.unknowpupil.common.core.exceptions.HealthException;
import cn.unknowpupil.common.core.utils.StringUtils;
import cn.unknowpupil.common.security.utils.SecurityUtils;
import cn.unknowpupil.domain.dto.TreeSelect;
import cn.unknowpupil.domain.dto.login.MetaVo;
import cn.unknowpupil.domain.dto.login.RouterVo;
import cn.unknowpupil.domain.system.SysMenu;
import cn.unknowpupil.domain.system.SysRole;
import cn.unknowpupil.domain.system.SysUser;
import cn.unknowpupil.mapper.system.SysMenuMapper;
import cn.unknowpupil.mapper.system.SysRoleMapper;
import cn.unknowpupil.service.system.ISysMenuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created at 2020-10-21 by  w10g <br>
 * Initialize SysMenu  ... <br>
 * 菜单权限表 核心业务处理实现类
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {


    @Resource
    private SysRoleMapper roleMapper;
    /**
     * 新增
     *
     * @param sysMenu {@link SysMenu}  菜单权限表
     * @return {@link SysMenu}
     */
    @Override
    public boolean create(SysMenu sysMenu) {
        checkMenuParam(sysMenu, true);
        return save(sysMenu);
    }


    /**
     * 详情
     *
     * @param id {@code Long}   SysMenu ID
     * @return {@link SysMenu}
     */
    @Override
    public SysMenu info(Long id) {
        return getById(id);
    }

    /**
     * 删除
     *
     * @param menuId {@code Long}   SysMenu ID
     * @return {@link SysMenu}
     */
    @Override
    public boolean delete(Long menuId) {
        Assert.isTrue(!hasChildByMenuId(menuId), "存在子菜单,不允许删除");
        int i = baseMapper.checkMenuExistRole(menuId);
        Assert.isTrue(i==0, "菜单已分配,不允许删除");
        return removeById(menuId);
    }
    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     * @return 结果
     */

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     * @return 结果
     */
    public boolean hasChildByMenuId(Long menuId) {
        Integer result = baseMapper.selectCount(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getParentId, menuId));
        return result > 0 ? true : false;
    }

    /**
     * 修改
     *
     * @param sysMenu {@link SysMenu}  菜单权限表
     * @return {@link SysMenu}
     */
    @Override
    public boolean update(SysMenu sysMenu) {
        checkMenuParam(sysMenu, false);
        return updateById(sysMenu);
    }

    /**
     * 验证参数
     *
     * @param sysMenu
     * @param isSave
     */
    private void checkMenuParam(SysMenu sysMenu, boolean isSave) {
        boolean b = checkMenuNameUnique(sysMenu);
        if (!b) {
            throw new HealthException("新增菜单'" + sysMenu.getMenuName() + "'失败，菜单名称已存在");
        }
        if (UserConstants.YES_FRAME == sysMenu.getIsFrame()
                && !StringUtils.startsWithAny(sysMenu.getPath(), SecurityConstants.HTTP, SecurityConstants.HTTPS)) {
            throw new HealthException("新增菜单'" + sysMenu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        if (!isSave) {
            if (sysMenu.getId().equals(sysMenu.getParentId())) {
                throw new HealthException("修改菜单'" + sysMenu.getMenuName() + "'失败，上级菜单不能选择自己");
            }
        }
    }

    /**
     * 判断菜单是否唯一
     *
     * @param menu
     * @return 唯一 true 不唯一 false
     */
    private boolean checkMenuNameUnique(SysMenu menu) {
        Long menuId = StringUtils.isNull(menu.getId()) ? -1L : menu.getId();
        SysMenu info = baseMapper.selectOne(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getMenuName, menu.getMenuName()).eq(SysMenu::getParentId, menu.getParentId()));
        if (StringUtils.isNotNull(info) && !info.getId().equals(menuId)) {
            return false;
        }
        return true;
    }


    @Override
    public Set<String> selectMenuPermsByUserId(Long id) {

        List<String> perms = baseMapper.selectMenuPermsByUserId(id);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysMenu> selectMenuTreeByUserId(Long id) {
        List<SysMenu> menus = null;
        if (SecurityUtils.isAdmin(id)) {
            menus = baseMapper.selectMenuTreeAll();
        } else {
            menus = baseMapper.selectMenuTreeByUserId(id);
        }
        return getChildPerms(menus, 0);
    }

    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden(UserConstants.YES_VISIBLE.equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getIsCache() == 1));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && cMenus.size() > 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect(UserConstants.NO_REDIRECT);
                router.setChildren(buildMenus(cMenus));
            } else if (isMeanFrame(menu)) {
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getIsCache() == 1));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
        List<SysMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
            if (StringUtils.isNotBlank(menu.getMenuName())) {
                wrapper.like(SysMenu::getMenuName, menu.getMenuName());
            }
            if (StringUtils.isNotBlank(menu.getVisible())) {
                wrapper.eq(SysMenu::getMenuName, menu.getVisible());
            }
            if (StringUtils.isNotBlank(menu.getStatus())) {
                wrapper.eq(SysMenu::getStatus, menu.getStatus());
            }
            wrapper.orderByAsc(SysMenu::getParentId, SysMenu::getOrderNum);

            menuList= baseMapper.selectList(wrapper);
        }else {
            menuList= baseMapper.selectMenuListByUserId(menu,userId);
        }
        return menuList;

    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<SysMenu> selectMenuList(Long userId) {
        return selectMenuList(new SysMenu(), userId);
    }

    @Override
    public List<Long> selectMenuListByRoleId(Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return baseMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    public List<SysMenu> buildMenuTree(List<SysMenu> menus)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysMenu dept : menus)
        {
            tempList.add(dept.getId());
        }
        for (Iterator<SysMenu> iterator = menus.iterator(); iterator.hasNext();)
        {
            SysMenu menu = (SysMenu) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    private List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = Lists.newArrayList();
        for (Iterator<SysMenu> iterator = list.iterator(); iterator.hasNext(); ) {
            SysMenu t = (SysMenu) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    private boolean hasChild(List<SysMenu> list, SysMenu tChild) {
        return getChildList(list, tChild).size() > 0 ? true : false;
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu menu) {
        List<SysMenu> tlist = new ArrayList<SysMenu>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = (SysMenu) it.next();
            if (n.getParentId().longValue() == menu.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMeanFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMeanFrame(SysMenu menu) {
        return menu.getParentId().intValue() == UserConstants.YES_PARENT && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame()==UserConstants.NO_FRAME;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (UserConstants.YES_FRAME == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME == menu.getIsFrame()) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMeanFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMeanFrame(menu)) {
            component = menu.getComponent();
        }
        return component;
    }
}
